//
//  CNBBSConst.m
//  BBSModule
//
//  Created by 邓建东 on 2020/5/12.
//  Copyright © 2020 dong. All rights reserved.
//

#import "CNViewConst.h"
#import "CSDNUser.h"
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseTool/UUIDTool.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

// 修改收藏夹名称
NSString *const CNMineCollectFolderEditSuccessNotification = @"CNMineCollectFolderEditSuccessNotification"; 
//收藏过博文
NSString *const kIsHaveCollectionAction = @"kIsHaveCollectionAction";
//收藏引导时间
NSString *const kShowGuideTime = @"kShowGuideTime";

@implementation CNViewConst

+(NSString *)getCSDNMD5Key
{
    NSString * appVersion=kAPPVersion/*[mAPPVersion substringToIndex:3]*/;
    NSString * md5key=[NSString stringWithFormat:@"csdn-ios-%@",appVersion];
    md5key = [[self stringFromMD5WithString:md5key] uppercaseString];
    
    if(md5key.length>24){
        md5key=[md5key substringToIndex:24];
    }else if(md5key.length<24){
        for (int i=0;i<24-md5key.length; i++) {
            [md5key stringByAppendingString:@"0"];
        }
    }
    return  md5key;
}

+(NSString *)getLoginCSDNMD5Key
{
    NSString * appVersion=kAPPVersion/*[mAPPVersion substringToIndex:3]*/;
    NSString * md5key=[NSString stringWithFormat:@"csdn-ios-%@",appVersion];
    md5key = [[self stringFromMD5WithString:md5key] uppercaseString];
    
    return  md5key;
}


+ (NSString *)stringFromMD5WithString:(NSString *)string{
    
    if(string == nil || [string length] == 0)
        return nil;
    
    const char *value = [string UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    
    return outputString;
}


/**
 修改论坛返回的body
 
 @param htmlStr html代码
 @param fontSize 字体大小
 @param fitImageSize 图片大小
 @return 返回html
 */
+(NSString *)convertHtmlFromBodyString:(NSString *)htmlStr fontSize:(CGFloat)fontSize fitImageSize:(BOOL)fitImageSize{
    if (htmlStr.length == 0 || !htmlStr) {
        return @"";
    }
    NSString * body= htmlStr;
    
    if([body rangeOfString:@"<fieldset"].location != NSNotFound)
    {
        
        
        body = [body stringByReplacingOccurrencesOfString:@"<fieldset>" withString:@"<div class = \"quote\">"];
        body = [body stringByReplacingOccurrencesOfString:@"</fieldset><br />\n<br />\n" withString:@"</div>"];
        body = [body stringByReplacingOccurrencesOfString:@"</fieldset><br />\n" withString:@"</div>"];
        body = [body stringByReplacingOccurrencesOfString:@"</fieldset>" withString:@"</div>"];
        body = [body stringByReplacingOccurrencesOfString:@"<blockquote>" withString:@""];
        body = [body stringByReplacingOccurrencesOfString:@"<legend class=\"font_bold\">" withString:@"<p class=\"bbs\">"];
        body = [body stringByReplacingOccurrencesOfString:@"<legend>" withString:@"<p class=\"bbs\">"];
        body = [body stringByReplacingOccurrencesOfString:@"</legend>" withString:@"<br />\n"];
        
        unsigned int  i = 0;
        while ([body rangeOfString:@"<div class = \"quote\">"].location != NSNotFound) {
            NSRange r = [body rangeOfString:@"<div class = \"quote\">"];
            NSString * str = [NSString stringWithFormat:@"<div style= \"background-color:#%2x%2x%2x; padding:5px; color:#989DAD; font-size:12px; margin:5px;\">",i,i,i];
            
            body = [body stringByReplacingOccurrencesOfString:@"<div class = \"quote\">" withString: str options:NSRegularExpressionSearch range:NSMakeRange(0,r.location+r.length)];
            i++;
        }
    }
    
    int color = [CNThemesManager isNight]?0xDADFE8:(0x2A2D33);
    
    int backgroundColor = [CNThemesManager isNight]?0x2A2D33:(0xFFFFFF);
    
    //内容 css 添加
    body = [body rangeOfString:@"<head>"].location == NSNotFound? [NSString stringWithFormat:@"<html><head><meta charset=\"UTF-8\"><link href=\"detail.css\" type=\"text/css\" rel=\"stylesheet\" /><style type=\"text/css\">p{line-height:1.5;font-size:%.1fpx;color:#%x;margin-left:0px;padding-right:0px;text-align:justify;}blockquote.bbs-quote{display:inline;border:none;color:#%x;padding:0px;margin:0px;} </style></head><body><div style=\"font-size:%.1fpx;background:#%x;color:#%x;\">%@</div></body></html>",fontSize,color,color,fontSize,backgroundColor,color,body]:body;
    //]
    return body;
}


+(NSArray *)addAtAttributeWithString:(NSMutableAttributedString *)attributedStr{
    // 匹配 @用户名
    NSMutableArray *array = [NSMutableArray array];
    [attributedStr enumUBBTag:@"at" usingBlock:^(NSRange tagRange, NSMutableAttributedString * _Nonnull tagContent, NSMutableAttributedString * _Nonnull currentStr, BOOL * _Nonnull stop) {
        NSDictionary *dic = [CSDNTool dictionaryWithJsonString:tagContent.string];
        if (!dic && !dic[@"n"] && !dic[@"u"]) {
            tagContent.yy_font = attributedStr.yy_font;
            tagContent.yy_color = attributedStr.yy_color;
            [currentStr replaceCharactersInRange:tagRange withAttributedString:tagContent];
            return ;
        }
        [array addObject:dic];
        [dic setValue:[NSString stringWithFormat:@"%@ ",[dic[@"n"] stringByTrim]] forKey:@"n"];
        NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"@%@",dic[@"n"]]?:@""];
        replace.yy_font = attributedStr.yy_font;
        replace.yy_color = [UIColor colorFromHexCode:@"#4788C7"];
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        // 数据信息，用于稍后用户点击
        highlight.userInfo = @{kDynamicLinkAtName : dic[@"u"]?:@""}; 
        [replace yy_setTextHighlight:highlight range:NSMakeRange(0, replace.length)];
        [currentStr replaceCharactersInRange:tagRange withAttributedString:replace];
    }];
    return [[NSArray alloc] initWithArray:array];
}

// @用户名 转换成[at]{"u":"theo789","n":"天天开心"}[/at]格式
+ (NSString *)replaceAtUsername:(NSString *)atString atUserArray:(NSArray *)atUserArray{
    for (NSDictionary *dict in atUserArray) {
        NSString *username = [NSString stringWithFormat:@"@%@",dict[@"n"]];
        if ([atString containsString:username]) {
            
            NSString *toString = [NSString stringWithFormat:@"[at]{\"%@\":\"%@\",\"%@\":\"%@\"}[/at]",@"u",dict[@"u"],@"n",dict[@"n"]];
            
            toString =  [toString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
            
            atString  =  [atString stringByReplacingOccurrencesOfString:username withString:toString];
        }
    }
    return atString;
}
+ (NSAttributedString *)_attachmentWithFontSize:(CGFloat)fontSize image:(UIImage *)image shrink:(BOOL)shrink {
    
    //    CGFloat ascent = YYEmojiGetAscentWithFontSize(fontSize);
    //    CGFloat descent = YYEmojiGetDescentWithFontSize(fontSize);
    //    CGRect bounding = YYEmojiGetGlyphBoundingRectWithFontSize(fontSize);
    
    // Heiti SC 字体。。
    CGFloat ascent = fontSize * 0.86;
    CGFloat descent = fontSize * 0.14;
    CGRect bounding = CGRectMake(0, -0.14 * fontSize, fontSize, fontSize);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(ascent - (bounding.size.height + bounding.origin.y), 0, descent + bounding.origin.y, 0);
    
    YYTextRunDelegate *delegate = [YYTextRunDelegate new];
    delegate.ascent = ascent;
    delegate.descent = descent;
    delegate.width = bounding.size.width;
    
    YYTextAttachment *attachment = [YYTextAttachment new];
    attachment.contentMode = UIViewContentModeScaleAspectFit;
    attachment.contentInsets = contentInsets;
    attachment.content = image;
    
    if (shrink) {
        // 缩小~
        CGFloat scale = 1 / 10.0;
        contentInsets.top += fontSize * scale;
        contentInsets.bottom += fontSize * scale;
        contentInsets.left += fontSize * scale;
        contentInsets.right += fontSize * scale;
        contentInsets = YYTextUIEdgeInsetPixelFloor(contentInsets);
        attachment.contentInsets = contentInsets;
    }
    
    NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken];
    [atr yy_setTextAttachment:attachment range:NSMakeRange(0, atr.length)];
    CTRunDelegateRef ctDelegate = delegate.CTRunDelegate;
    [atr yy_setRunDelegate:ctDelegate range:NSMakeRange(0, atr.length)];
    if (ctDelegate) CFRelease(ctDelegate);
    
    return atr;
}

/**
 替换评论中的表情
 
 @param text 评论内容
 @param fount 字号
 @param color 颜色
 @param lineSpacing 行间距
 @return 替换后的字符串
 */
+(NSMutableAttributedString *)processCommentContent:(NSString *)text Fount:(UIFont *)fount Color:(UIColor *)color LineSpacing:(CGFloat)lineSpacing
{
    //转成可变属性字符串
    NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]initWithString:text];
    mAttributedString.yy_lineSpacing = lineSpacing;
    mAttributedString.yy_font = fount;
    mAttributedString.yy_color = color;
    //创建匹配正则表达式的类型描述模板
    NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
    //创建匹配对象
    NSError * error;
    NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    //判断
    if (!regularExpression)//如果匹配规则对象为nil
    {
        DDLogDebug(@"正则创建失败！");
        DDLogDebug(@"error = %@",[error localizedDescription]);
        return nil;
    }
    else
    {
        NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
        //开始遍历 逆序遍历
        for (NSInteger i = resultArray.count - 1; i >= 0; i --)
        {
            //获取检查结果，里面有range
            NSTextCheckingResult * result = resultArray[i];
            //根据range获取字符串
            NSString * rangeString = [mAttributedString.string substringWithRange:result.range];
            NSString *imageName =  rangeString;
            if (imageName)
            {
                //获取图片
                NSString *imageNames = [[[NSBundle bundleForClass:[self class]] pathForResource:@"Sticker" ofType:@"bundle"] stringByAppendingPathComponent:imageName];
                UIImage * image = [YYImage imageWithContentsOfFile:imageNames];
                //这是个自定义的方法
                if (image != nil)
                {
                    YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
                    imageView.width = 20;
                    imageView.height = 20;
                    NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:fount alignment:YYTextVerticalAlignmentCenter];
                    //开始替换
                    [mAttributedString replaceCharactersInRange:result.range withAttributedString:attachText];
                }
            }
        }
    }
    
    return mAttributedString;
}

+ (BOOL)canEidtorAction{
//    return [[CSDNConst getUserStatus] isEqualToString:@"normal"];
    return YES;
}
///deleted 账号已封杀
///activateAndRisk 待激活且养号
///activate 待激活
///riskControl 养号
///normal 正常账号
+ (id)getActionVC{
    return nil;
}


+ (BOOL)csdnIsAudit
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"csdnIsAudit"];
}
/**
 是否是登录用户
 
 */
+(BOOL)isLoginUserName:(NSString *)userName{
    return [userName.lowercaseString isEqualToString:[CSDNUser currentUser].username.lowercaseString];
}

+(NSString *)getCSDNAccessToken
{
    NSString *accessToken = [NSString stringWithFormat:@"%@%@%@%@",CN_UUID,@"iOS",@"CSDN-APP",@"b85fF96d-7Aa4-4Ec1-bf1D-2133c1A45656"];
    accessToken = [self stringFromMD5WithString:accessToken];
    return accessToken;
}
+ (BOOL)blogBottomShowAB {
    NSData* data  = [[NSUserDefaults standardUserDefaults] objectForKey:@"iOS_BlogBottomBar_IsA"];
    BOOL isA = [[NSKeyedUnarchiver unarchiveObjectWithData:data] boolValue];
    return isA;
}

+ (NSArray *)qrCodeHostList
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"qrCodeHostList"];
}
//保存收藏状态 收藏时间
+ (void)saveCollectionAction{
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsHaveCollectionAction];
     [[NSUserDefaults standardUserDefaults] synchronize];
    
    [CNViewConst saveShowGuideTime];
}
//保存展示弹框的时间
+ (void)saveShowGuideTime{
    NSTimeInterval timeStamp = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [[NSUserDefaults standardUserDefaults] setDouble:timeStamp forKey:kShowGuideTime];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


+(BOOL)isLogin{
//    return [self loginStatus];
    return YES;
}

+ (BOOL)loginStatus
{
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    return [[userdefault objectForKey:KLoginStatus] boolValue];
}

+ (void)loginOut {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:KLoginStatus];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kOtherLoginUserName];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kOtherLoginOpenId];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSessionId];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLoginType];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCSDNToken];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserToken];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"systemNotifyUnreadCount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"commentNotifyUnreadCount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"supportNotifyUnreadCount"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"followNotifyUnreadCount"];
    //清除标签设置记录
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"showInterestTagTime"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"showInterestTimes"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"settingUserInterestTag"];
    
    //清除cookie
    [CSDNTool removeWebCookie];
}


+ (NSString *)auditToken
{
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    return [userdefault objectForKey:@"auditToken"];
}

+ (NSString *)auditUserToken
{
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    return [userdefault objectForKey:@"auditUserToken"];
}

+(NSString *)userToken
{
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    return [userdefault objectForKey:kUserToken];
}

+ (BOOL)routeUrl:(NSString *)url navigationVc:(UINavigationController *)nav refer:(NSString *)refer trackingCode:(NSString *)trackingCode urlParams:(NSDictionary *)urlParams vipReferrer:(NSString *)vipReferrer exts:(NSDictionary *)exts{
    return YES;
//    if (![routerUrl isValid]) {
//        return NO;
//    }
//    NSURL *urlStr = [NSURL URLWithString:routerUrl];
//    if (!urlStr) {
//        return NO;
//    }
//
//    if ([urlStr.scheme isEqualToString:@"csdnweb"]) {
//        routerUrl = [routerUrl replaceCharcter:@"https" withCharcter:@"csdnweb"];
//        CNWKWebViewController *web = [[CNWKWebViewController alloc]initWithUrl:routerUrl];
//        web.isProgressView = YES;
//        web.isClose = YES;
//        [nav pushViewController:web animated:YES];
//        return YES;
//    }
//    if ([urlStr.scheme isEqualToString:@"csdnapp"]) {
//        if ([FFRouter canRouteURL:routerUrl]) {
//            [FFRouter routeURL:routerUrl withParameters:@{@"refer":refer?:@"",@"trackingCode":trackingCode?:@"",@"nav":nav?:[[CNNavigationController alloc]init],@"urlParams":urlParams?:@{},@"vipRefer":vipReferrer?:@"",@"exts":exts?:@{}}];
//            return YES;
//        }else{
//            return NO;
//        }
//    }
//    if ([urlStr.scheme isEqualToString:@"csdnflutter"]) {
//        CNFlutterRouter *flutterRouter = [CNFlutterRouter sharedRouter];
//        flutterRouter.navigationController = nav;
//        [flutterRouter open:routerUrl urlParams:@{} exts:exts completion:^(BOOL finished) {
//
//        }];
//        return YES;
//    }
//    [self tapSkipDetailWithUrl:url AndNavigationController:nav AndDownloadUrl:nil AndReferer:refer AndTrackingCode:trackingCode urlParams:urlParams vipReferrer:vipReferrer];
//
//    return YES;
}


void cn_swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector)
{
    // the method might not exist in the class, but in its superclass
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    // class_addMethod will fail if original method already exists
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    
    // the method doesn’t exist and we just added one
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }
    else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
}

@end
